package com.situ.stmall.admin.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.situ.stmall.admin.entity.APIResult;
import com.situ.stmall.admin.entity.Root;
import com.situ.stmall.admin.service.RootService;
import com.situ.stmall.admin.util.TokenUtil;
import com.situ.stmall.admin.util.TokenUtil.Token;

@RestController
@RequestMapping("/api/roots")
@CrossOrigin(origins = {"*"})
public class RootController {
	
	@Autowired
	private RootService rootService;

	/**
	 * 登录
	 */
	@GetMapping
	public APIResult login(Root root, String vercode, String token) {
		//1、获取参数
		APIResult apiResult = new APIResult();
		//判断vercode是否正确
		Token tkn = TokenUtil.parseToken(token);
		if (tkn.getStatus() == 1) {
			apiResult.setStatus(404);
			apiResult.setMsg("验证码已过期");
			return apiResult;
		}	
		
		if (!vercode.toUpperCase().equals(tkn.getCode())) {
			apiResult.setStatus(404);
			apiResult.setMsg("验证码错误");
			
			return apiResult;
		}
		
		//2、调用service层
		try {
			Root loginRoot = rootService.login(root);
			//清除密码数据
			loginRoot.setPassword(null);
			//登录成功
			//保存到Token中
			String loginToken = TokenUtil.createToken(loginRoot.getRootname());
			
			//返回数据
			apiResult.setStatus(200);
			apiResult.setData(loginRoot);
			apiResult.setMsg(loginToken);
		} catch (Exception e) {
			e.printStackTrace();
			//登录失败
			//返回数据
			apiResult.setStatus(404);
			apiResult.setMsg(e.getMessage());
		}
		
		//3、返回数据
		return apiResult;
	}
	
	@GetMapping("/{token}")
	public APIResult get(@PathVariable("token") String strToken) {
		//解析token字符串
		Token token = TokenUtil.parseToken(strToken);
		
		//根据用户名，查询当前登录的用户
		Root root = rootService.getByRootName(token.getCode());
		root.setPassword(null);
		return APIResult.ok(root);
	}
	
	/**
	 * 退出
	 */
	@DeleteMapping
	public APIResult logout(HttpSession session) {
		
		session.invalidate();
		
		APIResult apiResult = new APIResult();
		apiResult.setStatus(204);
		
		return apiResult;
	}
	
	/**
	 * 修改
	 */
	@PutMapping
	public APIResult edit(@RequestBody Root root) {
		
		APIResult apiResult = new APIResult();
		
		root = rootService.edit(root);
		
		if (root != null) {
			apiResult.setStatus(201);
			apiResult.setData(root);
		}else {
			apiResult.setStatus(404);
			apiResult.setMsg("你要修改的管理员信息不存在");
		}
		
		
		return apiResult;
	}
}
